/**
 * 
 * @authors youzhao.zhou@pandauu.com
 * @date    2016-09-08 15:12:44
 * @version $Id$
 * 
 * 车票兑换页
 * 
 */

;(function(root,factory){

  var dependent = {
    zepto : typeof exports !== 'undefined' ? require('./zepto.js')&&root.$ : root.$,
    underscore : typeof exports !== 'undefined' ? require('../../public_src/js/underscore/underscore.js') : root._,
    Project : typeof exports !== 'undefined' ? require('../../public_src/js/1_self/1_project.js') : root.Project,
    conf : typeof exports !== 'undefined' ? require('../../public_src/js/1_self/2_config.js') : root.conf,
    log : typeof exports !== 'undefined' ? require('../../public_src/js/1_self/3_log.js') : root.p_log,
    path: {
      zepto : '../../p_src/js/convert/zepto.js',
      underscore : '../../public_src/js/underscore/underscore.min',
      Project : '../../public_src/js/1_self/1_project',
      conf : '../../public_src/js/1_self/2_config',
      log : '../../public_src/js/1_self/3_log',
    }
  };
  
  if(typeof exports === 'object' && typeof module === 'object'){

    module.exports = factory(exports,
      dependent.zepto, 
      dependent.underscore,
      dependent.Project, 
      dependent.conf,
      dependent.log
    );

  } else if (typeof define === 'function' && define.amd) {
    // AMD. Register as an anonymous module.

    define(['exports', 
      dependent.path.zepto, 
      dependent.path.underscore,
      dependent.path.Project, 
      dependent.path.conf,
      dependent.path.log
      ], factory);
  } else if (typeof exports === 'object' && typeof exports.nodeName !== 'string') {
    // CommonJS
    factory(exports, 
      dependent.zepto, 
      dependent.underscore,
      dependent.Project, 
      dependent.conf,
      dependent.log
    );
  } else {
    // Browser globals
    if (!(dependent.Project||dependent.conf||dependent.log)) {
      throw('请加载相应的文件！');
    }
    factory({},
      dependent.zepto, 
      dependent.underscore,
      dependent.Project, 
      dependent.conf,
      dependent.log
    );
  }

})((typeof window !== 'undefined' ? window : this) ,function(exports,$ ,_ , Project, conf, log, undefined){
  'use strict';

  setTimeout(function(){

    if (typeof $ === 'undefined') {
      $ = window.$;
    }

    if (typeof _ === 'undefined') {
      _ = window._;
    }

    /*
      调试开关
    */
    log._logToggle(true);

    var urlConf = conf._conf;
    /*
      项目工具类对象
    */
    var project = new Project();

    /*
      设置导航头部
    */
    project.setHTML('.middle', '标签列表');

    var params = project.getQueryStringObj();

    /*
      填充会话ID
    */

    $('#threadId').val(params.thread_id);

    $('.jsLabel').attr({
      'data-id': params.thread_id
    });

    var labelData = new Label();
    getTagListAjax({thread_id: params.thread_id});
    /*
      获取标签列表
    */

    function getTagListAjax(data){
      $.ajax({
        url: urlConf.apiRoot + urlConf.apiPre.one + urlConf.api.tagList,
        type: 'GET',
        dataType: 'json',
        data: data
      })
      .done(function(data) {
        if (data.code === 0) {
          labelData.setLabel(data.data);
          $('.jsLabelContainer').html(_.template($('#labelTpl').html())({list: labelData}));
          addEvent();
          log._log(labelData);
        }else{
          $('#fail').removeClass('s-hide');
          $('.js-warn-content').html(data.msg);
          addCloseEvent('.js-fail');
        }
        
      })
      .fail(function() {
        log._log("error");
      })
      .always(function() {
        log._log("complete");
      });
    }

    /*
      启动弹框关闭按钮
    */
    function addCloseEvent(selector){
      $(selector).unbind('click').bind('click', function(event) {
        /* Act on the event */
        $($(this).data('target')).addClass('s-hide');

        $(selector).unbind('click');
      });
    }

    function Label(){
      this.self = [];
      this.other = [];
      this.noUse = [];
    }

    Label.prototype.setLabel = function (data, serviceName){
      var temp = null;
      for(var k in data){
        temp = {};
        temp.id = data[k].id||'';
        temp.content = data[k].tag||'';
        temp.time = data[k].create_time||'';
        temp.color = data[k].color||'';
        temp.type = data[k].type||3;

        if (+temp.type === 1) {
          temp.name = '我自己';
          temp.type = 1;
          this.self.push(temp);
        }else if(+temp.type === 2){
          temp.name = data[k].nickname;
          temp.type = 2;
          this.other.push(temp);
        }else{
          temp.name = '';
          temp.type = 3;
          this.noUse.push(temp);
        }
      }
    }

    /*
      数据结构
    */
    var test = {
      self: [
        {
          id: 1,
          content: '暴脾气',
          name: '我自己',
          time: '2016-09-19 12:32',
          color: '#50d1c1',
          type: 1,
        }
      ],
      other: [
        {
          id: 2,
          content: '暴脾气',
          name: '熊猫盼盼',
          time: '2016-09-19 12:32',
          color: '#50d1c1',
          type: 2,
        }
      ],
      noUse: [
        {
          id: 3,
          content: '暴脾气',
          name: '',
          time: '',
          color: '#50d1c1',
          type: 3,
        }
      ],
      select: [
        {
          
        }
      ]
    };


    function addEvent(){
      var type = [];
      $('.jsLabel').on('click', function(event) {
        event.preventDefault();
        var target = $(event.target);
        var eventType = target.data('event');

        log._log(target);
        switch(eventType){
          case 'label':
            target = target.parent();
          case 'li':
            
            if (!!target.data('other')) {

              return false;
            }

            if (target.hasClass(target.data('select'))) {
              target.find('.label-item').css({
                'background-color': '#fff',
                'color': target.find('.label-item').data('color')
              });
              target.find('input').val('');
              target.removeClass(target.data('select'));
            }else{
              target.find('.label-item').css({
                'background-color': target.find('.label-item').data('color'),
                'color': '#fff'
              });
              target.find('input').val(target.data('id'));
              target.addClass(target.data('select'));
            }
            
            break;
          case 'use':

          sendLabel($('#labelData').serialize());

            break;
        }


      });
    }
    
    function sendLabel(data){
      $.ajax({
        url: urlConf.apiRoot + urlConf.apiPre.one + urlConf.api.addTag,
        type: 'POST',
        dataType: 'json',
        data: data
      })
      .done(function(data) {
        if (data.code === 0) {
          log._log(data);
          window.history.back();
        }else{
          $('#fail').removeClass('s-hide');
          $('.js-warn-content').html(data.msg);
          addCloseEvent('.js-fail');
        }
        
      })
      .fail(function() {
        log._log("error");
      })
      .always(function() {
        log._log("complete");
      });
    }

    window.addEventListener('unload',function(){
      log = null;
    },false);

  },0);

});
